<?php

namespace App\Member\Controllers;

use Illuminate\Http\Request;
use App\Models\AdminUser;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Callout;
use App\Member\Metrics\Examples\AgentBalances;
use App\Member\Metrics\Examples\TradeBalance;
use App\Member\Metrics\Examples\InvestmentAmount;
use App\Handlers\Team;
use Dcat\Admin\Admin;
use App\Member\Renderables\TeamRenderables;
use Endroid\QrCode\QrCode;
use App\Member\Metrics\Examples\TotalUsers;
use App\Member\Metrics\Examples\NewUsers;
use App\Member\Metrics\Examples\NewDevices;
use Dcat\Admin\Widgets\Box;
use App\Member\Renderables\AdminUserRenderables;
use App\Member\Renderables\AdminUserPieRenderables;
use App\Member\Renderables\AdminUserHeaderRenderables;




class AdminUserController extends BaseController
{


    public function test()
    {
        // 标题和内容
        $box = Box::make('标题', '内容');

        // 设置间距
        $box->padding('0 15px 0 12px');

        // 设置工具按钮
        $box->tool('<button class="btn btn-sm btn-light shadow-none">按钮</button>');

        // 设置收缩按钮
        $box->collapsable();

        // 设置移除按钮
        $box->removable();
    }
    /**
     * Index interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function index(Content $content)
    {
        if (request(IFrameGrid::QUERY_NAME)) {
            return $content->body($this->iFrameGrid());
        }

        return $content
            ->title(trans('handlers.admin_user_grzlxxxx'))
            ->description(' ')
            //->description($this->description()['index'] ?? trans('admin.list'))
            ->body(function ($row) {
                $row->column(12, new AdminUserHeaderRenderables());
            })
            ->body(function($row) {
            })
            ->body(function($row){
                $row->column(12, new AdminUserRenderables());
//                $row->column(6, new AdminUserPieRenderables());
            })
            ->row(function (Row $row) {
                $row->column(6, function (Column $column){

                    $column->append($this->detail($this->getUser()->id));
                });
                $row->column(6, function (Column $column){
                    $url = request()->root().'/user/register/?fromuser='.Admin::user()->username;

                    $callout = Callout::make(trans('handlers.admin_user_khljxxxx').'&nbsp;&nbsp;&nbsp;&nbsp;<a style="color:#838ed3" href="'.$url.'" target="_blank">'
                        .$url.'</a>', trans('handlers.admin_user_wdtgxxxx'))->primary()->removable();

                    $qrCode = new QrCode($url);
                    $aa = '<img src="'.$qrCode->writeDataUri().'" height="280" />';
                    $callout1 = Callout::make($aa, trans('handlers.admin_user_tgewmxxx'))->primary()->removable();
                    $column->append(new AdminUserPieRenderables());
                    $column->append($callout);
                    $column->append($callout1);
                });
            });
//            ->tab(function($tab){
//
//            });
            //->body($this->build());
    }


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AdminUser(), function (Grid $grid) {

            $grid->id->sortable();
            $grid->username;
            $grid->password;
            $grid->name;
            $grid->avatar;
            $grid->remember_token;
            $grid->created_at;
            $grid->updated_at->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });
        });
    }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
//        $tree->disableCreateButton();
//        $tree->disableEditButton();
        return Show::make($id, new AdminUser(), function (Show $show) use ($id) {

            $show->name();
            $show->en_name();
            $show->username()->label();
            $show->mt_login();
            $show->tjr_id()->as(function($q){
                if ($q == 0){
                    return '公司帐户';
                }
                return AdminUser::where('id',$q)->first()->username;
            });
            $show->phone();
            $show->email();
            $show->profit_rate();
            $show->sfz_id()->label();
            $show->sfz_zimg()->image('', '', 30);
            $show->sfz_fimg()->image('', '', 30);
            $show->bank_number();
            $show->bank_type();
            $show->bank_address();
            $show->swift_code();
            $show->is_lock()->using([1 => trans('handlers.admin_user_zcxxxxxx'), 2 => trans('handlers.admin_user_sdxxxxxx')])->dot([
                    1 => 'primary',
                    2 => 'danger',
                ]);
            $show->is_auth()->using([trans('handlers.admin_user_wrzxxxxx'), trans('handlers.admin_user_yrzxxxxx')])->dot(['danger','primary']);
            //$show->avatar('头像')->image();
            //$show->is_withdrawal('是否投出');
            //$show->investment_amount('投入数量');
            //$show->trade_balance('出售产品');
            //$show->agent_balance('停售产品');

            $show->disableListButton();
            $show->panel()
                ->style('danger')
                ->title(' ')->tools(function ($tools) use ($id) {
                    $tools->disableDelete();
                    $tools->disableEdit();

                    Form::dialog(trans('handlers.admin_user_grzlbjxx'))
                        ->click('.create-form') // 绑定点击按钮
                        ->url('admin_user/'.$id.'/edit') // 表单页面链接，此参数会被按钮中的 “data-url” 属性替换。。
                        ->width('700px') // 指定弹窗宽度，可填写百分比，默认 720px
                        ->height('90%') // 指定弹窗高度，可填写百分比，默认 690px
                        ->success('Dcat.reload()'); // 新增成功后刷新页面

                    $lang = trans('handlers.admin_user_xgzlmmxx');
                    // 当需要在同个“class”的按钮中绑定不同的链接时，把链接放到按钮的“data-url”属性中即可
                    //$editPage = admin_base_path('admin_user/'.$id.'/edit');
                    $tools->append("<div style=''><span class='btn btn-success create-form'>{$lang}</span></div>"); // 新增成功后刷新页面
                });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

        return Form::make(new AdminUser(), function (Form $form) {

            $form = $this->formButton($form);


            $form->tab(trans('handlers.admin_user_yhxxxxxx'), function($form){
                $userTable = config('admin.database.users_table');
                $connection = config('admin.database.connection');
                $id = $form->getKey();

                $form->text('username')->disable();
                //->required()->creationRules(['required', "unique:{$connection}.{$userTable}"])
                //->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
                if ($form->model()->username){
                    $form->text('mt_login')->disable();
                }else{
                    $form->text('mt_login')->required()
                        ->updateRules(['required', "unique:{$connection}.{$userTable},mt_login,$id"]);;
                }
                $form->text('name')->disable();
                $form->text('en_name')->disable();
                $form->text('sfz_id')->disable();
                $form->text('phone')->type('num');
                $form->text('email')->rules('email',['email' => trans('handlers.admin_user_bshfyxxx')]);
                $form->text('password')->customFormat(function(){
                    return '';
                });
                $form->text('pay_password')->customFormat(function(){
                    return '';
                });
            })->tab(trans('handlers.admin_user_yhxxxxxx'), function($form){
                //$form->image('avatar','头像')->autoUpload();
                $form->text('sfz_id')->disable();
                $form->text('bank_number')->disable();
                $form->text('bank_type')->disable();
                $form->text('bank_address')->disable();
                $form->text('swift_code')->disable();
                //$form->image('sfz_zimg', '身份证正面')->autoUpload();
                //$form->image('sfz_fimg','身份证正面')->autoUpload();
                //$form->switch('is_lock','帐号状态');
                //$form->text('is_auth','是否认证资料');
                //$form->text('is_withdrawal','是否投出');
                //$form->text('profit_rate','结算比例');
                //$form->text('investment_amount','投入数量');
                //$form->text('trade_balance','出售产品');
                //$form->text('agent_balance','停售产品');
            });

            $form->saving(function($form){
                if (!$form->password) {
                    $form->deleteInput('password');
                }else{
                    $form->dry_passwork = encrypt(config('app.dry_passwork').$form->password);
                    $form->password     = bcrypt($form->password);
                }
                if (!$form->pay_password) {
                    $form->deleteInput('pay_password');
                }else{
                    $form->pay_password = bcrypt($form->pay_password);
                }

                if ($form->getKey() != $this->getUser()->id){
                    return $form->error(trans('handlers.admin_user_csywbkxg'));
                }
            });
        });
    }



    public function userteam(Content $content)
    {
        // 添加面包屑导航
        $content->breadcrumb(
            ['text' => trans('handlers.admin_user_tdglxxxx'), 'url' => '/user_team'],
            ['text' => '']
        );

        return $content
            ->title(trans('handlers.admin_user_tdglxxxx'))
            ->description('')
            //->description($this->description()['index'] ?? trans('admin.list'))
            ->body(new TeamRenderables());
    }

    protected function team_data(Request $request)
    {
        // 搜索功能
        $account = $request->account ?? $this->getUser()->username;
        $type    = $request->type;      // type 为 1 把自身数组加上去
        $times   = $request->times;     // 时间查询

        // 搜索功能 只搜索直推的人
        $queryUser = AdminUser::where('username', $account)->first();// 查询用户
        if (!$queryUser) {
            return self::returnJson('', -1, trans('handlers.admin_user_wcyhxxxx'));
        }
        if (!Team::isVerifyUserUp($queryUser)){
            return self::returnJson('', -1, trans('handlers.admin_user_csywxxxx'));
        }

        // 查询 子孙数组
        $new = Team::treeToData2($account , $type , $times);
        if ($new){
            return array("code" => 0, "msg" => trans('handlers.admin_user_cxcgxxxx'),"data" => $new);
        }else{
            return array("code" => -1, "msg" => trans('handlers.admin_user_cxsbxxxx'),"data" => '');
        }
    }


    /***
     * 查询用户投入流水
     * @param Request $request  接收的查询参数
     * @return \Illuminate\Http\JsonResponse
     */
    protected function my_money(Request $request)
    {
        // 搜索功能 只搜索直推的人
        $queryUser = AdminUser::with(['deposite'])->where('id', $request->admin_user)->first();// 查询用户

        if (!Team::isVerifyUserUp($queryUser)){
            return self::returnJson('', 2, trans('handlers.admin_user_csywxxxx'));
        }

        $deposite = $queryUser->deposite->whereIn('type',[1,2]);
        $str = Team::getUserOrder($deposite);

        if (!empty($str)){
            return self::returnJson($str, 1);

        }else{
            return self::returnJson('');
        }
    }
}
